package com.keon.jianbao.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePopupWindow;
import com.keon.jianbao.AppContext;
import com.keon.jianbao.AppManager;
import com.keon.jianbao.R;
import com.keon.jianbao.adapter.UploadImgAdapter;
import com.keon.jianbao.api.Api;
import com.keon.jianbao.api.SimpleHandler;
import com.keon.jianbao.base.BaseActivity;
import com.keon.jianbao.bean.Result;
import com.keon.jianbao.ui.widget.EditTextLayout;
import com.keon.jianbao.ui.widget.NoScrollGridView;
import com.keon.jianbao.util.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;

import butterknife.Bind;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by keon on 2015/9/17.
 */
public class ActivityPublishActivity extends BaseActivity {

    public static final int REQUEST_PICK_PHOTO = 1;
    public static final int MAX_UPLOAD_IMAGE_NUM = 3;

    TextView tvTime = null;
    TimePopupWindow pwTime;
    UploadImgAdapter adapter;
    ArrayList<String> uploadImgs;

    @Bind(R.id.activity_publish_activity_image)
    NoScrollGridView nsgvImage;
    @Bind(R.id.activity_publish_name)
    EditTextLayout etlName;
    @Bind(R.id.activity_publish_place)
    EditTextLayout etlPlace;
    @Bind(R.id.activity_publish_hold_unit)
    EditTextLayout etlHoldUnit;
    @Bind(R.id.activity_publish_linkman)
    EditTextLayout etlLinkman;
    @Bind(R.id.activity_publish_activity_linkinfo)
    EditTextLayout etlLinkInfo;
    @Bind(R.id.activity_publish_enroll_start)
    TextView tvEnroolStart;
    @Bind(R.id.activity_publish_enroll_end)
    TextView tvEnroolEnd;
    @Bind(R.id.activity_publish_activity_start)
    TextView tvActivityStart;
    @Bind(R.id.activity_publish_activity_end)
    TextView tvActivityEnd;
    @Bind(R.id.activity_publish_activity_intro)
    EditText etIntro;
    @Bind(R.id.activity_publish_submit)
    Button bSubmit;

    AsyncHttpResponseHandler uploadImagesHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {

                    JSONArray ja = new JSONArray(new JSONObject(result.getContent()).getString("images"));
                    String[] images = new String[ja.length()];
                    for (int i = 0; i < ja.length(); i++) {
                        images[i] = ja.get(i).toString();
                    }

                    Api.activity_add(AppContext.getInstance().getProperty("user.code"), etlName.getText(), etlPlace.getText(),
                            etlHoldUnit.getText(), etlLinkman.getText(), tvEnroolStart.getText().toString(), tvEnroolEnd.getText().toString(),
                            tvActivityStart.getText().toString(), tvActivityEnd.getText().toString(), etIntro.getText().toString(), images,
                            etlLinkInfo.getText().toString(), activityAddHandler);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    AsyncHttpResponseHandler activityAddHandler = new SimpleHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            super.onSuccess(statusCode, headers, responseBody);
            Result result = null;
            try {
                result = new Result(responseBody);
                if (result.getStatus() > 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("type", 0);
                    JSONObject jo = new JSONObject(result.getContent());
                    bundle.putString("url", jo.getString("url"));
                    ActivityPublishActivity.showToast(result.getTips());
                    AppManager.getAppManager().finishActivity();
                    jump(WebActivity.class, bundle);
                } else {
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_activity_publish;
    }

    @Override
    protected int getToolBarTitle() {
        return R.string.activity_publish;
    }

    @Override
    public void initView() {
        initGridView();
        initTimeChooser();
        tvEnroolStart.setOnClickListener(this);
        tvEnroolEnd.setOnClickListener(this);
        tvActivityStart.setOnClickListener(this);
        tvActivityEnd.setOnClickListener(this);
        bSubmit.setOnClickListener(this);

    }

    @Override
    public void initData() {
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.activity_publish_enroll_start:
                pwTime.showAtLocation(tvEnroolStart, Gravity.BOTTOM, 0, 0, new Date());
                tvTime = tvEnroolStart;
                break;
            case R.id.activity_publish_enroll_end:
                pwTime.showAtLocation(tvEnroolEnd, Gravity.BOTTOM, 0, 0, new Date());
                tvTime = tvEnroolEnd;
                break;
            case R.id.activity_publish_activity_start:
                pwTime.showAtLocation(tvActivityStart, Gravity.BOTTOM, 0, 0, new Date());
                tvTime = tvActivityStart;
                break;
            case R.id.activity_publish_activity_end:
                pwTime.showAtLocation(tvActivityEnd, Gravity.BOTTOM, 0, 0, new Date());
                tvTime = tvActivityEnd;
                break;
            case R.id.activity_publish_submit:
                if (check()) {
                    try {
                        File[] imgs = new File[uploadImgs.size()];
                        for (int i = 0; i < uploadImgs.size(); i++) {
                            imgs[i] = new File(uploadImgs.get(i));
                        }
                        showWaitDialog();
                        Api.upload_activity_images(AppContext.getInstance().getProperty("user.code"), imgs, uploadImagesHandler);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    private void initGridView() {
        adapter = new UploadImgAdapter(MAX_UPLOAD_IMAGE_NUM);

        nsgvImage.setAdapter(adapter);
    }

    private void initTimeChooser() {
        //时间选择器
        pwTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
        //时间选择后回调
        pwTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                if (tvTime != null) {
                    tvTime.setText(StringUtils.getTime(date, "yyyy-MM-dd HH:mm:ss"));
                }

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_PICK_PHOTO:
//                ArrayList<String> images = data.getStringArrayListExtra(Constant.EXTRA_PHOTO_PATHS);
                ArrayList<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                uploadImgs = images;
                adapter.updateData(images);
//                mAdaper.swapDatas(images);
                break;
        }
    }

    private boolean check() {

        if (uploadImgs != null && uploadImgs.size() > 0) {
        } else {
            showToast(R.string.activity_publish_activity_image_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etlName.getText())) {
            showToast(R.string.activity_publish_name_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etlPlace.getText())) {
            showToast(R.string.activity_publish_place_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etlHoldUnit.getText())) {
            showToast(R.string.activity_publish_hold_unit_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etlLinkman.getText())) {
            showToast(R.string.activity_publish_linkman_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etlLinkInfo.getText())) {
            showToast(R.string.activity_publish_activity_linkinfo_error_null);
            return false;
        }
        if (tvEnroolStart.getText() == getString(R.string.activity_publish_enroll_start)) {
            showToast(R.string.activity_publish_enroll_start_error_null);
            return false;
        }
        if (tvEnroolEnd.getText() == getString(R.string.activity_publish_enroll_end)) {
            showToast(R.string.activity_publish_enroll_end_error_null);
            return false;
        }
        if (tvActivityStart.getText() == getString(R.string.activity_publish_activity_start)) {
            showToast(R.string.activity_publish_enroll_start_error_null);
            return false;
        }
        if (tvActivityEnd.getText() == getString(R.string.activity_publish_activity_end)) {
            showToast(R.string.activity_publish_activity_end_error_null);
            return false;
        }
        if (StringUtils.isEmpty(etIntro.getText().toString())) {
            showToast(R.string.activity_publish_activity_intro_error_null);
            return false;
        }

        return true;
    }
}
